package com.party.mobile.biz.crowdfund;

import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.*;
import com.party.core.exception.BusinessException;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.activity.ActivityDetail;
import com.party.core.model.activity.CrowfundResources;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.counterfoil.CounterfoilBusiness;
import com.party.core.model.crowdfund.*;
import com.party.core.model.gift.GiftTarget;
import com.party.core.model.member.*;
import com.party.core.model.order.*;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.activity.IActivityDetailService;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.activity.ICrowfundResourcesService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.counterfoil.ICounterfoilBusinessService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.crowdfund.*;
import com.party.core.service.crowdfund.biz.CrowdfundReviseBizService;
import com.party.core.service.distributor.IDistributorDetailService;
import com.party.core.service.gift.IGiftTargetService;
import com.party.core.service.goods.IGoodsCouponsService;
import com.party.core.service.member.*;
import com.party.core.service.member.biz.MemberPersonalCountBizService;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.order.IOrderFormSubInfoService;
import com.party.core.service.order.IOrderTradeService;
import com.party.core.service.system.ISysConfigService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.mobile.biz.analyze.MemberCopartnerDetailBizService;
import com.party.mobile.biz.analyze.MemberMerchantDetailBizService;
import com.party.mobile.biz.file.FileBizService;
import com.party.mobile.jms.publisher.service.IOrderCancelPubulisherService;
import com.party.mobile.web.dto.crowdfund.input.ApplyInput;
import com.party.mobile.web.dto.crowdfund.input.SupportInput;
import com.party.mobile.web.dto.crowdfund.output.*;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.vdurmont.emoji.EmojiParser;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import javax.annotation.Nullable;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.net.URL;
import java.util.*;

import static com.party.mobile.biz.crowdfund.CrowdfundActivityBizService.logger;

/**
 * 众筹项目业务接口
 * Created by wei.li
 *
 * @date 2017/2/17 0017
 * @time 10:21
 */

@SuppressWarnings("all")
@Service
public class ProjectBizService {

    @Autowired
    private IProjectService projectService;

    @Autowired
    private ISupportService supportService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    private IOrderTradeService orderTradeService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private IActivityDetailService activityDetailService;

    @Autowired
    private ITargetProjectService targetProjectService;

    @Autowired
    private IProjectContentService projectContentService;

    @Autowired
    private IMemberActService memberActService;

    @Autowired
    private IAnalyzeService analyzeService;

    @Autowired
    private IMemberMerchantService memberMerchantService;

    @Autowired
    private IPartnerMemberService partnerMemberService;

    @Autowired
    private ICrowdfundRankService crowdfundRankService;

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private CosBizService cosBizService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private IMemberExternalAppService memberExternalAppService;

    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;

    @Autowired
    private IOrderCancelPubulisherService orderCancelPubulisherService;

    @Autowired
    private IProjectCommentService projectCommentService;

    @Autowired
    private MemberPersonalCountBizService memberPersonalCountBizService;

    @Autowired
    private IProjectApplyService projectApplyService;

    @Autowired
    private MemberMerchantDetailBizService memberMerchantDetailBizService;

    @Autowired
    private MemberCopartnerDetailBizService memberCopartnerDetailBizService;

    @Autowired
    private ISupportTransferService supportTransferService;

    @Autowired
    private ICrowfundResourcesService crowfundResourcesService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    PaintProjectPosterBiz paintProjectPosterBiz;

    @Autowired
    private IDistributorDetailService distributorDetailService;

    @Autowired
    private IProjectDetailCountService projectDetailCountService;

    @Autowired
    private IProjectLabelService projectLabelService;

    @Autowired
    private IGoodsCouponsService goodsCouponsService;//核销

    @Autowired
    private IProjectBrokerageService projectBrokerageService;

    @Autowired
    private IOrderFormSubInfoService orderFormSubInfoService;

    @Autowired
    private IGiftTargetService giftTargetService;

    @Autowired
    private IProjectGradationService projectGradationService;

    @Autowired
    private IEventGradationService eventGradationService;

    @Autowired
    private IProjectInfoGradationService projectInfoGradationService;

    @Autowired
    private ICounterfoilBusinessService counterfoilBusinessService;

    @Autowired
    private ICounterfoilService counterfoilService;

    @Autowired
    private IMemberGroupService memberGroupService;

    //众筹订单默认单位
    private static final int CROWD_FUND_UNIT = 1;

    //我支持的类型
    private static final Integer SUPPORT_TYPE = 1;

    //我发布的类型
    private static final Integer LAUNCH_TYPE = 0;

    // 默认公众号名称
    @Value("#{wechat['wechat.wwz.appname']}")
    private String appName;
    // 默认公众号头像链接
    @Value("#{wechat['wechat.wwz.headimgurl']}")
    private String headImgUrl;
    // 默认公众号二维码链接
    @Value("#{wechat['wechat.wwz.qrurl']}")
    private String qrUrl;

    @Autowired
    private CrowdfundReviseBizService crowdfundReviseBizService;

    //protected static Logger logger = LoggerFactory.getLogger(ProjectBizService.class);

    /**
     * 众筹自动报名
     *
     * @param activity 活动
     * @param source   资源众筹
     */
    public String apply(Activity activity, Project source, String counterfoilId) {
        ApplyParameter parameter = new ApplyParameter();
        parameter.setActivityId(activity.getId());
        parameter.setMemberId(source.getAuthorId());
        Member member = memberService.get(source.getAuthorId());
        parameter.setRealname(member.getRealname());
        parameter.setMobile(member.getMobile());
        parameter.setCompany(member.getCompany());
        parameter.setTitle(member.getJobTitle());
        parameter.setDeclaration(source.getDeclaration());
        parameter.setStyle(source.getStyle());
        parameter.setProjectTitle(activity.getTitle());
        String projectId = projectApplyService.apply(parameter, counterfoilId);

        // 更新机构统计数
        memberMerchantDetailBizService.updateApplyNum(activity.getMember());

        // 更新合作商统计数
        memberCopartnerDetailBizService.updateApplyNum(projectId);

        // 会员统计数
        memberPersonalCountBizService.updateCrowdfundNum(activity.getMember(), source.getAuthorId(), true);

        // 生成二维码
        try {
            String filePath = fileBizService.getUploadCIPath("crowdfund", source.getAuthorId());
            String content = "project/project_detail.html?id=" + projectId;
            String previewPicUrl = fileBizService.uploadCloudOut(projectId, filePath, content, activity.getMember());
            if (previewPicUrl == null) {
                logger.error("生成众筹详情二维码异常——众筹项目id= " + activity.getId() + "——众筹id=" + projectId);

            }
        } catch (Exception e) {
            logger.error("生成众筹详情二维码异常", e);
        }
        return projectId;
    }

    /**
     * 分页查询众筹项目
     *
     * @param type      列表类型（0:我众筹的 1:我支持的）
     * @param isSuccess 列表状态（0:众筹中 1:成功 2:失败）
     * @param page      分页参数
     * @return 项目列表
     */
    public List<ProjectListOutput> list(Integer type, Integer isSuccess, Page page, String currentId) {
        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();
        if (SUPPORT_TYPE.equals(type)) {
            projectWithAuthor.setSort(5);
            projectWithAuthor.setFavorerId(currentId);
            projectWithAuthor.setOrderStatus(Constant.SUPPORT_PAY_STATUS_SUCCESS);
        } else if (LAUNCH_TYPE.equals(type)) {
            // 众筹中，项目没有截止
            if (isSuccess == 0) {
                isSuccess = 12;
            } else if (isSuccess == 2) {
                isSuccess = 13;
            }
            if (new Integer(12).equals(isSuccess)) {
                // 众筹中，项目没有截止
                projectWithAuthor.setSort(0);
            } else if (new Integer(13).equals(isSuccess)) {
                // 众筹中，项目已截止
                projectWithAuthor.setSort(3);
            }
            projectWithAuthor.setAuthorId(currentId);
        }
        projectWithAuthor.setIsSuccess(isSuccess);
        projectWithAuthor.setDelFlag(BaseModel.DEL_FLAG_NORMAL);

        List<ProjectWithAuthor> projectWithAuthorList = Lists.newArrayList();
        if (SUPPORT_TYPE.equals(type)) {
            projectWithAuthorList = projectService.listForMySupport(projectWithAuthor, page);
        } else {
            projectWithAuthorList = projectService.listPage(projectWithAuthor, page);
        }
        boolean isConvertBase64 = sysConfigService.isConvertBase64();
        List<ProjectListOutput> projectListOutputList = LangUtils.transform(projectWithAuthorList, new Function<ProjectWithAuthor, ProjectListOutput>() {
            @Nullable
            @Override
            public ProjectListOutput apply(@Nullable ProjectWithAuthor projectWithAuthor) {
                ProjectListOutput projectListOutput = ProjectListOutput.transform(projectWithAuthor);
                if (isConvertBase64) {
                    projectListOutput.setDeclaration(StringUtils.decodeBase64New(projectListOutput.getDeclaration()));
                } else {
                    projectListOutput.setDeclaration(EmojiParser.parseToUnicode(projectListOutput.getDeclaration()));
                }

                if (SUPPORT_TYPE.equals(type)) {
                    Float myFavorerAmount = supportService.myFavorerAmount(currentId, projectWithAuthor.getId());
                    projectListOutput.setMyFavorerAmount(myFavorerAmount);
                }

                // 众筹项目详情二维码
                String filePath = fileBizService.getUploadCIPath(projectWithAuthor.getTargetAuthorId(), "zcActivity");
                String detailFileName = "detail_" + projectWithAuthor.getTargetId();
                String detailQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
                projectListOutput.setTargetQrCode(detailQrCodeUrl);

//                if (projectWithAuthor.getActualAmount() <= new Float(0.0f)) {
//                    projectListOutput.setFavorerOutputList(new ArrayList<FavorerOutput>());
//                } else {
//                    //查询支持列表
//                    SupportWithMember supportWithMember = new SupportWithMember();
//                    supportWithMember.setProjectId(projectWithAuthor.getId());
//                    supportWithMember.setPayStatus(Constant.IS_SUCCESS);
//                    List<SupportWithMember> supportWithMemberList = supportService.listWithMember(supportWithMember, new Page(1, 8));
//                    List<FavorerOutput> favorerOutputList = LangUtils.transform(supportWithMemberList, new Function<SupportWithMember, FavorerOutput>() {
//                        @Nullable
//                        @Override
//                        public FavorerOutput apply(@Nullable SupportWithMember supportWithMember) {
//                            return FavorerOutput.transform(supportWithMember);
//                        }
//                    });
//                    projectListOutput.setFavorerOutputList(favorerOutputList);
//                }
                return projectListOutput;
            }
        });
        return projectListOutputList;
    }

    /**
     * 获取众筹详情
     *
     * @param id          编号
     * @param currentUser 当前用户
     * @return 项目详情
     */
    public ProjectOutput getDetails(String id, CurrentUser currentUser) {
        ProjectWithAuthor projectWithAuthor = projectService.getWithAuthor(id);
        if (null == projectWithAuthor || projectWithAuthor.getDelFlag().equals("1")) {
            throw new BusinessException(PartyCode.IS_NO_DATA, "该众筹项目不存在");
        }

        ProjectOutput projectOutput = ProjectOutput.transform(projectWithAuthor);
        //剩余资金
        float surplusAmount = (float) (Math.round((projectWithAuthor.getTargetAmount() - projectWithAuthor.getActualAmount()) * 100) / 100);//如果要求精确4位就*10000然后/10000;
        projectOutput.setSurplusAmount(surplusAmount);

        //众筹支持转移
        SupportTransfer supportTransfer = supportTransferService.getBySourceId(id);
        if (null != supportTransfer && supportTransfer.getIsAuthorized() == 0) {
            Activity activity = activityService.get(supportTransfer.getTargetId());
            if (!"1".equals(activity.getDelFlag())) {
                projectOutput.setTargetId(supportTransfer.getTargetId());
                projectOutput.setSourceId(id);
                projectOutput.setIsAuthorized(supportTransfer.getIsAuthorized());
            }
        }
        //根据众筹查找众筹众筹目标
        TargetProject targetProject = targetProjectService.findByProjectId(projectWithAuthor.getId());
        projectOutput.setTargeId(targetProject.getTargetId());
        projectOutput.setDescribe(projectWithAuthor.getRemarks());

        //项目详情
        Activity activity = activityService.get(targetProject.getTargetId());
        if (null == activity) {
            throw new BusinessException("众筹目标不存在");
        }
        projectOutput.setEndTime(activity.getEndTime());

        //验证众筹是否到期
        Integer result = DateUtils.compareDate(new Date(), activity.getEndTime());
        if (result == 1) {
            projectOutput.setClosed(true);
        }

        // 所有支持者众筹
        String eventId = null;
        String targetId = null;
        if (!Strings.isNullOrEmpty(activity.getEventId())) {
            eventId = activity.getEventId();
        } else {
            targetId = activity.getId();
        }
        Integer beCrowdfundNum
                = projectService.numOfSupport(eventId, targetId, projectWithAuthor.getId());
        projectOutput.setBeCrowdfundNum(beCrowdfundNum);
        projectOutput.setTargetAuthorId(activity.getMember());
        projectOutput.setTitle(activity.getTitle());
        projectOutput.setPic(activity.getPic());

        //报名相关
        ActivityDetail activityDetail = activityDetailService.getByRefId(targetProject.getTargetId());
        if (null != activityDetail) {
            projectOutput.setApplyRelated(StringEscapeUtils.unescapeHtml4(activityDetail.getApplyRelated()));
            projectOutput.setMatchStandard(StringEscapeUtils.unescapeHtml4(activityDetail.getMatchStandard()));
            projectOutput.setContent(StringEscapeUtils.unescapeHtml4(activityDetail.getContent()));
        }

        //跑马灯
        List<CrowfundResources> picList = crowfundResourcesService.findByRefId(activity.getId(), "1");
        projectOutput.setPicList(picList);

        //是不是自己的项目
        boolean isMy = false;
        if (null != currentUser && currentUser.getId().equals(projectWithAuthor.getAuthorId())) {
            isMy = true;
        }
        projectOutput.setMy(isMy);

        if (null != currentUser) {
            //是否报名过
            MemberAct memberAct = memberActService.findByMemberAct(currentUser.getId(), targetProject.getTargetId());
            if (null != memberAct) {
                TargetProject myTargetProject = targetProjectService.findByOrderId(memberAct.getOrderId());
                Project project = projectService.get(myTargetProject.getProjectId());
                if (null != project) {
                    projectOutput.setMyProjectId(project.getId());
                    projectOutput.setMyPayType(project.getPayType());
                }
            }
        }

        // 众筹成功海报图片路径
        String posterFilePath = String.format("%s/%s/", projectWithAuthor.getAuthorId(), "zcPoster");
        String posterUrl = cosBizService.getPreviewPictureUrl2(posterFilePath + projectWithAuthor.getId(), "png");
        projectOutput.setPosterUrl(posterUrl);

        //获取要关注的公众号信息
        Map<String, Object> data = new HashMap<String, Object>();
        String memberId = activity.getMember();
        if (StringUtils.isNotEmpty(memberId)) {
            MemberGroup member = memberGroupService.getPartner(memberId);
            //MemberMerchant memberMerchant = memberMerchantService.findByMemberId(memberId);
            if (member != null && member.getOpenStatus().equals(YesNoStatus.YES.getCode())) {
                if (member.getMandatoryAttention().equals(YesNoStatus.YES.getCode())) {
                    MemberExternalApp memberExternalApp
                            = memberExternalAppService.findByMemberIdAndDeployType(member.getId(),
                            member.getDeployType());
                    WechatOpenMember wechatOpenMember
                            = wechatOpenMemberService.get(memberExternalApp.getExternalAccountId());
                    data.put("qrUrl", wechatOpenMember.getQrcodeUrl());
                    data.put("headImg", wechatOpenMember.getHeadImg());
                    data.put("appName", wechatOpenMember.getNickName());
                }
            } else {
                data.put("qrUrl", qrUrl);
                data.put("headImg", headImgUrl);
                data.put("appName", appName);
            }
        }
        projectOutput.setPublicInfo(data);

        String activityId = activity.getId();
        List<GiftTarget> giftTargets = giftTargetService.findByTargetId(activityId);
        if (giftTargets.size() > 0) {
            projectOutput.setShowGift(YesNoStatus.YES.getCode());
        } else {
            projectOutput.setShowGift(YesNoStatus.NO.getCode());
        }
        return projectOutput;
    }

    /**
     * 查询众筹支持列表
     *
     * @param page      分页参数
     * @param projectId 项目编号
     * @return 众筹支持列表
     */
    public List<SupportOutput> listSupport(Page page, String projectId, String memberId, String targetId) {

        Project project = projectService.get(projectId);
        Member author = memberService.get(project.getAuthorId());
        SupportWithMember supportWithMember = new SupportWithMember();
        supportWithMember.setProjectId(projectId);
        supportWithMember.setAuthorId(project.getAuthorId());
        supportWithMember.setMemberId(memberId);
        supportWithMember.setStatus(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode());
        List<SupportWithMember> supportWithMemberList = supportService.listWithComment(supportWithMember, page);

        boolean isConvertBase64 = sysConfigService.isConvertBase64();
        List<SupportOutput> supportOutputList = LangUtils.transform(supportWithMemberList, new Function<SupportWithMember, SupportOutput>() {
            @Nullable
            @Override
            public SupportOutput apply(@Nullable SupportWithMember supportWithMember) {
                SupportOutput supportOutput = SupportOutput.transform(supportWithMember);
                List<ProjectCommentOutput> commentOutputList = LangUtils.transform(supportWithMember.getProjectCommentList(),
                        new Function<ProjectComment, ProjectCommentOutput>() {
                            @Nullable
                            @Override
                            public ProjectCommentOutput apply(@Nullable ProjectComment projectComment) {
                                ProjectCommentOutput projectCommentOutput = new ProjectCommentOutput();
                                String comment = projectComment.getComment();
                                if (StringUtils.isNotEmpty(comment)) {
                                    if (isConvertBase64) {
                                        comment = StringUtils.decodeBase64New(comment);
                                    } else {
                                        comment = EmojiParser.parseToUnicode(comment);
                                    }
                                }
                                projectCommentOutput.setComment(comment);
                                projectCommentOutput.setCommentName(author.getRealname());
                                projectCommentOutput.setId(projectComment.getId());
                                projectCommentOutput.setReplyName(supportWithMember.getFavorerName());
                                projectCommentOutput.setTargetId(supportWithMember.getFavorerId());
                                return projectCommentOutput;
                            }
                        });

                List<ProjectCommentOutput> newCommentList = new ArrayList<>();
                // 查询支持者回复众筹者的评论
                if (!CollectionUtils.isEmpty(commentOutputList)) {
                    for (int i = 0, j = commentOutputList.size(); i < j; i++) {
                        ProjectCommentOutput p = commentOutputList.get(i);
                        ProjectComment param = new ProjectComment();
                        param.setReplyId(p.getId());
                        List<ProjectComment> list = projectCommentService.listPage(param, null);
                        if (!CollectionUtils.isEmpty(list)) {
                            ProjectCommentOutput newComment = new ProjectCommentOutput();
                            ProjectComment r = list.get(0);
                            String comment = r.getComment();
                            if (StringUtils.isNotEmpty(comment)) {
                                if (isConvertBase64) {
                                    comment = StringUtils.decodeBase64New(comment);
                                } else {
                                    comment = EmojiParser.parseToUnicode(comment);
                                }
                            }
                            newComment.setComment(comment);
                            newComment.setCommentName(supportWithMember.getFavorerName());
                            newComment.setId(r.getId());
                            newComment.setReplyName(author.getRealname());
                            newComment.setReplyId(r.getReplyId());
                            newComment.setTargetId(author.getId());

                            p.setIsReply(1);
                            p.setIsCrowdfunder(1);
                            newCommentList.add(p);
                            newComment.setIsCrowdfunder(0);
                            newCommentList.add(newComment);
                        } else {
                            p.setIsReply(0);
                            p.setIsCrowdfunder(1);
                            newCommentList.add(p);
                        }
                        if (newCommentList.size() == 4) {
                            break;
                        } else if (newCommentList.size() > 4) {
                            newCommentList = newCommentList.subList(0, 4);
                            break;
                        }
                    }
                }

                supportOutput.setReplyList(newCommentList);
                if (StringUtils.isNotEmpty(supportOutput.getComment())) {
                    if (isConvertBase64) {
                        supportOutput.setComment(StringUtils.decodeBase64New(supportOutput.getComment()));
                    } else {
                        supportOutput.setComment(EmojiParser.parseToUnicode(supportOutput.getComment()));
                    }
                }
                return supportOutput;
            }
        });
        //List<SupportOutput> supportList = new ArrayList<>();
        //如果登入进来的人和报名众筹的人不是同一个，那他只能报名众筹设置的所有人都可以看的支持者
        //if (!memberId.equals(project.getAuthorId())) {
            for (SupportOutput supportOutput : supportOutputList) {
                //if (supportOutput.getSupportSwitch() == 0) {
                    //查询支持者是否在同一项目下有报名
                    Project project1 = projectService.getProjectByMemberId(supportOutput.getId(), targetId);
                    if (project1 != null) {
                        //代表显示“支持ta”图标
                        supportOutput.setSupportHimSwitch(0);
                        supportOutput.setSupporterProjectId(project1.getId());
                    } else {
                        //代表不显示“支持ta”图标
                        supportOutput.setSupportHimSwitch(1);
                    }
                    //supportList.add(supportOutput);
               // }
            }
            return supportOutputList;
       // }

        //如果走到了这里   代表是自己看自己  那就设置一下“支持ta”图标 显示与否
//        for (SupportOutput supportOutput : supportOutputList) {
//            //查询支持者是否在同一项目下有报名
//            Project project1 = projectService.getProjectByMemberId(supportOutput.getId(), targetId);
//            if (project1 != null) {
//                //代表显示“支持ta”图标
//                supportOutput.setSupportHimSwitch(0);
//                supportOutput.setSupporterProjectId(project1.getId());
//            }else {
//                //代表不显示“支持ta”图标
//                supportOutput.setSupportHimSwitch(1);
//            }
//            supportList.add(supportOutput);
//        }
//        return supportList;
    }

    /**
     * 众筹支持
     *
     * @param supportInput 输入视图
     * @param currentUser  当前用户
     * @return 订单号
     */
    @Transactional
    public String[] support(SupportInput supportInput, CurrentUser currentUser) {
        if (supportInput.getMoney() < new Float(0.01f)) {
            throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "金额最低为0.01");
        }
        Double amount = projectService.getMaxAmount(supportInput.getProjectId());
        try {
            logger.info("支持：剩余金额--{}；支持金额--{}", amount, supportInput.getMoney());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (BigDecimalUtils.round(supportInput.getMoney(), 2) > BigDecimalUtils.round(amount.floatValue(), 2)) {
            throw new BusinessException(PartyCode.CROWDFUNF_SUPPORT_PASS, "支持金额不能大于众筹剩余金额");
        }
        //校正众筹数据
        this.revise(supportInput.getProjectId());

        //生成订单
        Member member = memberService.get(currentUser.getId());
        OrderForm orderForm = new OrderForm();
        ProjectInfoGradation byProjectId = projectInfoGradationService.findByProjectId(supportInput.getProjectId());
        if(byProjectId == null){
            //众筹者是单场的
            orderForm.setType(OrderType.ORDER_CROWD_FUND.getCode());
        }else {
            //众筹者是多场的
            orderForm.setType(OrderType.ORDER_MULTIPLE_CROWD_FUND.getCode());
        }
        orderForm.setMemberId(currentUser.getId());
        orderForm.setGoodsId(supportInput.getProjectId());
        orderForm.setUnit(CROWD_FUND_UNIT);
        orderForm.setLinkman(member.getUsername());
        orderForm.setPhone(member.getMobile());
        orderForm.setStatus(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
        orderForm.setIsPay(PaymentState.NO_PAY.getCode());
        orderForm.setPayment(supportInput.getMoney());
        Project project = projectService.get(supportInput.getProjectId());
        if (StringUtils.isNotEmpty(project.getId())) {
            TargetProject targetProject = targetProjectService.findByProjectId(project.getId());
            if (targetProject.getType().equals(Constant.CROWD_FUND_TYPE_ACTIVITY)) {
                Activity activity = activityService.get(targetProject.getTargetId());
                orderForm.setInitiatorId(activity.getMember()); // 众筹项目发起者
                orderForm.setTitle(activity.getTitle());
            }
        }

        String id = orderFormService.insert(orderForm);

        try {
            OrderFormSubInfo formSubInfo = new OrderFormSubInfo();
            formSubInfo.setOrderId(orderForm.getId());
            if (null != member) {
                formSubInfo.setAuthorLogo(member.getLogo());
                formSubInfo.setAuthorName(member.getRealname());
            }

            MemberGroup initiator = memberGroupService.get(orderForm.getInitiatorId());
            if (null != initiator) {
                formSubInfo.setInitiatorLogo(initiator.getLogo());
                formSubInfo.setInitiatorName(initiator.getRealname());
            }
            orderFormSubInfoService.insert(formSubInfo);
        } catch (Exception e) {
            logger.error("保存订单附属信息异常", e);
        }

        //持久化支持
        Support support = SupportInput.transform(supportInput);

        support.setOrderId(id);
        support.setFavorerId(currentUser.getId());
        if (StringUtils.isNotEmpty(support.getComment())) {
            if (sysConfigService.isConvertBase64()) {
                support.setComment(StringUtils.encodeBase64(support.getComment()));
            } else {
                support.setComment(EmojiParser.parseToAliases(support.getComment()));
            }
        }
        String supportId = supportService.insert(support);

        if (StringUtils.isNotEmpty(id)) {
//            orderCancelPubulisherService.send(id);
        }
        return new String[]{orderForm.getId(), supportId};
    }


    /**
     * 手机端删除众筹
     *
     * @param id 众筹编号
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean delete(String id) {
        boolean endResult = true;
        String memberId = null;
        try {
            if (StringUtils.isEmpty(id)) {
                endResult = false;
                return endResult;
            }
            Project project = projectService.get(id);
            if (project == null) {
                endResult = false;
                return endResult;
            }
            memberId = project.getAuthorId();
//            //删除分销信息
//            DistributorDetail distributorDetail = distributorDetailService.findByTargetId(id);
//            if (null != distributorDetail) {
//                DistributorCount distributorCount
//                        = distributorCountService.findByRelationId(distributorDetail.getDistributorRelationId());
//                if (null != distributorCount) {
//                    distributorCount.setCrowdfundNum(distributorCount.getCrowdfundNum() - 1);
//                    distributorCount.setApplyNum(distributorCount.getApplyNum() - 1);
//                    distributorCountService.update(distributorCount);
//                }
//                distributorDetailService.delete(distributorDetail.getId());
//            }

            //众筹关系
            TargetProject targetProject = targetProjectService.findByProjectId(id);
            if (null != targetProject) {

                //修改众筹项目
                Activity activity = activityService.get(targetProject.getTargetId());
                if (Constant.IS_CROWFUND_ING.equals(project.getIsSuccess())) {
                    activity.setBeCrowdfundNum(activity.getBeCrowdfundNum() - 1);
                }
                activity.setJoinNum(activity.getJoinNum() - 1);
                activityService.update(activity);

                //删除报名记录
                MemberAct memberAct = memberActService.findByOrderId(targetProject.getOrderId());
                if (memberAct != null) {
                    // 核销码
                    goodsCouponsService.deleteByOrderId(memberAct.getOrderId());
                    memberActService.delete(memberAct.getId());
                }
                targetProjectService.delete(targetProject.getId());

                // 分佣
                ProjectBrokerage projectBrokerage = projectBrokerageService.findByProjectId(id);
                if (projectBrokerage != null) {
                    projectBrokerageService.delete(projectBrokerage.getId());
                }

                // 数据分析
                projectLabelService.deleteByProjectId(id);
                try {
//					memberPersonalCountBizService.updateCrowdfundNum(activity.getMember(), project.getAuthorId(), false);
                    PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(activity.getMember(), project.getAuthorId());
                    memberPersonalCountBizService.countOne(partnerMember);
                } catch (Exception e) {
                    logger.error("实时更新个人统计众筹数量异常", e);
                }
                // 删除众筹内容
                ProjectContent projectContent = projectContentService.get(project.getContentId());
                if (projectContent != null) {
                    projectContentService.delete(projectContent.getId());
                }

                // 众筹详情统计-数据分析
                projectDetailCountService.deleteByProjectId(id);

                // 众筹评论
                projectCommentService.deleteByRefId(id);

                // 众筹排名
                crowdfundRankService.deleteByProjectId(id);

                // 众筹支持者转移授权
                supportTransferService.deleteBySourceId(id);
                supportTransferService.deleteByTargetId(id);
            }

            //删除票据报名关系，修改票据报名数量
            CounterfoilBusiness counterfoilBusiness = counterfoilBusinessService.findByBusinessId(id);
            if(null != counterfoilBusiness){
                Counterfoil counterfoil = counterfoilService.get(counterfoilBusiness.getCounterfoilId());
                if(null != counterfoil){
                    counterfoil.setJoinNum(counterfoil.getJoinNum() - 1);
                    counterfoilService.update(counterfoil);
                }
                counterfoilBusinessService.deleteByBusinessId(id);
            }

            Analyze analyze = analyzeService.findByTargetId(id);
            if (null != analyze) {
                analyzeService.delete(analyze.getId());
            }

            //删除众筹
            projectService.delete(id);
        } catch (Exception e) {
            endResult = false;
            logger.error("删除众筹失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            if (endResult) {
                try {
                    String filePath = fileBizService.getUploadCIPath("directPay", memberId);
                    String cosFilePath = CosBizService.getDeleteQrCodePath(filePath, id);
                    cosBizService.deleteFile(cosFilePath);
                } catch (Exception e) {
                    logger.error("删除众筹二维码失败", e);
                }
            }
        }
        return endResult;
    }


    /**
     * 查询活动下的众筹
     *
     * @param isSuccess 是否筹集成功
     * @param targetId  目标编号
     * @param page      分页参数
     * @return 众筹列表
     */
    public List<ProjectForActivityOutput> projectForActivityList(boolean isSuccess, String targetId, Page page) {
        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();

        //众筹成功？
        Integer success = isSuccess ? 1 : 0;
        projectWithAuthor.setIsSuccess(success);
        projectWithAuthor.setTargetId(targetId);
        // 不按照众筹截止时间排序
        projectWithAuthor.setSort(2);
        List<ProjectWithAuthor> projectWithAuthorList = projectService.listPage(projectWithAuthor, page);
        return this.transformOutput(projectWithAuthorList);
    }

    /**
     * 查询活动下兄弟活动的众筹
     *
     * @param isSuccess 是否筹集成功
     * @param targetId  目标编号
     * @param page      分页参数
     * @return 众筹列表
     */
    public List<ProjectForActivityOutput> projectForBrotherList(boolean isSuccess, String targetId, Page page) {
        Activity activity = activityService.get(targetId);
        if (null == activity || Strings.isNullOrEmpty(activity.getEventId())) {
            return Collections.EMPTY_LIST;
        }

        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();
        //众筹成功？
        Integer success = isSuccess ? 1 : 0;
        projectWithAuthor.setIsSuccess(success);
        projectWithAuthor.setExcludeTargetId(targetId);
        projectWithAuthor.setEventId(activity.getEventId());
        List<ProjectWithAuthor> projectWithAuthorList = projectService.listPage(projectWithAuthor, page);
        return this.transformOutput(projectWithAuthorList);
    }

    /**
     * 活动下所有的众筹
     *
     * @param isSuccess 是否筹集成功
     * @param targetId  目标编号
     * @param page      分页参数
     * @return 众筹列表
     */
    public List<ProjectForActivityOutput> projectForAllList(boolean isSuccess, String targetId, Page page) {
        Activity activity = activityService.get(targetId);
        if (null == activity) {
            return Collections.EMPTY_LIST;
        }

        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();
        if (Strings.isNullOrEmpty(activity.getEventId())) {
            projectWithAuthor.setTargetId(targetId);
        } else {
            projectWithAuthor.setEventId(activity.getEventId());
        }

        //众筹成功？
        Integer success = isSuccess ? 1 : 0;
        projectWithAuthor.setIsSuccess(success);
        List<ProjectWithAuthor> projectWithAuthorList = projectService.listPage(projectWithAuthor, page);
        return this.transformOutput(projectWithAuthorList);
    }

    /**
     * 查询联合发起下的众筹
     *
     * @param isSuccess   是否众筹成功
     * @param representId 联合发起编号
     * @param page        分页参数
     * @return 众筹列表
     */
    public List<ProjectForActivityOutput> projectForRepresentList(boolean isSuccess, String representId, Page page) {
        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();

        //众筹成功？
        Integer success = isSuccess ? 1 : 0;
        projectWithAuthor.setIsSuccess(success);
        projectWithAuthor.setRelationId(representId);
        List<ProjectWithAuthor> projectWithAuthorList = projectService.listPage(projectWithAuthor, page);
        return this.transformOutput(projectWithAuthorList);
    }


    /**
     * 查询活动下我的支持者的众筹
     *
     * @param isSuccess 是否众筹成功
     * @param projectId 众筹编号
     * @param page      分页参数
     * @return 众筹列表
     */
    public List<ProjectForActivityOutput> supportProjectList(boolean isSuccess, String projectId, Page page) {

        //查询该项目支持者
        Support support = new Support();
        support.setProjectId(projectId);
        List<Support> supportList = supportService.list(support);

        //是否存在支持者
        if (CollectionUtils.isEmpty(supportList)) {
            return Collections.EMPTY_LIST;
        }

        List<String> supportIds = LangUtils.transform(supportList, new Function<Support, String>() {
            @Nullable
            @Override
            public String apply(@Nullable Support support) {
                return support.getFavorerId();
            }
        });


        //众筹项目编号
        TargetProject targetProject = targetProjectService.findByProjectId(projectId);
        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();
        Integer success = isSuccess ? 1 : 0;
        projectWithAuthor.setIsSuccess(success);
        projectWithAuthor.setTargetId(targetProject.getTargetId());
        projectWithAuthor.setAuthorIds(Sets.newHashSet(supportIds));
        List<ProjectWithAuthor> projectWithAuthorList = projectService.listPage(projectWithAuthor, page);
        return this.transformOutput(projectWithAuthorList);
    }

    /**
     * 查询活动下我的支持者的众筹
     *
     * @param projectId 众筹编号
     * @param page      分页参数
     * @return 众筹列表
     */
    public List<ProjectForActivityOutput> supportProjectList(String projectId, Page page) {
        //查询该项目支持者
        SupportWithMember supportWithMember = new SupportWithMember();
        supportWithMember.setProjectId(projectId);
        supportWithMember.setPayStatus(Constant.IS_SUCCESS);
        List<SupportWithMember> supportWithMemberList = supportService.listWithMember(supportWithMember, null);

        //是否存在支持者
        if (CollectionUtils.isEmpty(supportWithMemberList)) {
            return Collections.EMPTY_LIST;
        }

        //众筹项目编号
        TargetProject targetProject = targetProjectService.findByProjectId(projectId);
        Activity activity = activityService.get(targetProject.getTargetId());
        if (null == activity) {
            return Collections.EMPTY_LIST;
        }

        List<String> supportIds = LangUtils.transform(supportWithMemberList, new Function<Support, String>() {
            @Nullable
            @Override
            public String apply(@Nullable Support support) {
                return support.getFavorerId();
            }
        });
        //众筹项目编
        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();
        if (Strings.isNullOrEmpty(activity.getEventId())) {
            projectWithAuthor.setTargetId(targetProject.getTargetId());
        } else {
            projectWithAuthor.setEventId(activity.getEventId());
        }
        projectWithAuthor.setAuthorIds(Sets.newHashSet(supportIds));
        List<ProjectWithAuthor> projectWithAuthorList = projectService.listPage(projectWithAuthor, page);
        return this.transformOutput(projectWithAuthorList);
    }

    /**
     * 转输出视图
     *
     * @param projectWithAuthorList 众筹列表
     * @return 输出视图列表
     */
    public List<ProjectForActivityOutput> transformOutput(List<ProjectWithAuthor> projectWithAuthorList) {
        boolean isConvertBase64 = sysConfigService.isConvertBase64();
        List<ProjectForActivityOutput> projectForActivityOutputList = LangUtils.transform(projectWithAuthorList, new Function<ProjectWithAuthor, ProjectForActivityOutput>() {
            @Nullable
            @Override
            public ProjectForActivityOutput apply(@Nullable ProjectWithAuthor projectWithAuthor) {
                //
                ProjectForActivityOutput projectForActivityOutput = ProjectForActivityOutput.transform(projectWithAuthor);
                if (projectWithAuthor.getActualAmount() <= new Float(0.0f)) {
                    projectForActivityOutput.setFavorerOutputList(new ArrayList<FavorerOutput>());
                } else {
                    //查询支持列表
                    SupportWithMember supportWithMember = new SupportWithMember();
                    supportWithMember.setProjectId(projectWithAuthor.getId());
                    supportWithMember.setPayStatus(Constant.IS_SUCCESS);
                    List<SupportWithMember> supportWithMemberList = supportService.listWithMember(supportWithMember, new Page(1, 8));
                    List<FavorerOutput> favorerOutputList = LangUtils.transform(supportWithMemberList, new Function<SupportWithMember, FavorerOutput>() {
                        @Nullable
                        @Override
                        public FavorerOutput apply(@Nullable SupportWithMember supportWithMember) {
                            return FavorerOutput.transform(supportWithMember);
                        }
                    });
                    projectForActivityOutput.setFavorerOutputList(favorerOutputList);
                }
                if (StringUtils.isNotEmpty(projectForActivityOutput.getDeclaration())) {
                    if (isConvertBase64) {
                        projectForActivityOutput.setDeclaration(StringUtils.decodeBase64New(projectForActivityOutput.getDeclaration()));
                    } else {
                        projectForActivityOutput.setDeclaration(EmojiParser.parseToUnicode(projectForActivityOutput.getDeclaration()));
                    }
                }
                return projectForActivityOutput;
            }
        });
        return projectForActivityOutputList;
    }

    /**
     * 插入众筹
     *
     * @param memberAct  活动报名
     * @param memberId   会员编号
     * @param applyInput 众筹宣言
     * @param payType    直接付款标志，不为空则为直接付款众筹类型
     * @return 众筹编号
     */
    @Transactional
    public String insert(MemberAct memberAct, String memberId, ApplyInput applyInput, Integer payType, Counterfoil counterfoil) {

        //持久化众筹
        Activity activity = activityService.get(memberAct.getActId());

        //是否是众筹活动
        if (!activity.getIsCrowdfunded().equals(Constant.IS_CROWDFUNDED)) {
            throw new BusinessException("该活动不是众筹类型");
        }
        Project project = new Project();
        project.setTitle(activity.getTitle());
        project.setTargetAmount(activity.getPrice());
        if(counterfoil != null){
            project.setTargetAmount(counterfoil.getPayment());
        }
        project.setPic(activity.getPic());
        project.setEndDate(activity.getEndTime());
        project.setDeclaration(applyInput.getDeclaration());
        project.setTitle(applyInput.getProjectTitle());
        project.setStyle(applyInput.getStyle());
        if (payType != null && payType == Constant.IS_DIRECTPAY_CROWDFUNDED)
            project.setPayType(payType); //当传入的payType为1时，表明当前为直接付款众筹类型
        String content = null;
        //活动详情
        ActivityDetail activityDetail = activityDetailService.getByRefId(activity.getId());
        if (null != activityDetail && null != activityDetail.getContent()) {
            content = activityDetail.getContent();
        }

        String id = projectContentService.insert(new ProjectContent(content));
        project.setContentId(id);
        project.setAuthorId(memberId);
        String projectId = projectService.insert(project);

        //报名分销
        String applyParentId
                = Strings.isNullOrEmpty(applyInput.getApplyParentId())
                ? activity.getMember() : applyInput.getApplyParentId();

        //持久化众筹关联
        TargetProject targetProject = new TargetProject();
        targetProject.setTargetId(activity.getId());
        targetProject.setOrderId(memberAct.getOrderId());
        targetProject.setProjectId(projectId);
        targetProject.setType(Constant.CROWD_FUND_TYPE_ACTIVITY);
        targetProject.setParentId(applyParentId);
        targetProject.setDistributorId(memberId);
        targetProjectService.insert(targetProject);

        //统计分析
        Analyze analyze = new Analyze();
        analyze.setTargetId(projectId);
        analyzeService.insert(analyze);

        return project.getId();
    }

    /**
     * 获取支持初始化数据
     *
     * @param projectId 项目编号
     * @return输出视图
     */
    public GetSupportInitOutput getSupportInit(String projectId) {
        GetSupportInitOutput getSupportInitOutput = new GetSupportInitOutput();
        //float num = projectService.getMaxAmount(projectId);
        TargetProject targetProject = targetProjectService.findByProjectId(projectId);
        Activity activity = activityService.get(targetProject.getTargetId());
        if (null == activity) {
            throw new BusinessException("众筹项目不存在");
        }
        CrowdfundEvent crowdfundEvent = crowdfundEventService.get(activity.getEventId());
        if (crowdfundEvent == null) {
            throw new BusinessException("众筹主题不存在");
        }
        getSupportInitOutput.setSwitchSupportRange(crowdfundEvent.getSwitchSupportRange());
        getSupportInitOutput.setSupportRange(crowdfundEvent.getSupportRange());
        //getSupportInitOutput.setMaxNum(num);
        getSupportInitOutput.setSupportDeclaration(activity.getSupportDeclaration());
        getSupportInitOutput.setActivityId(activity.getId());
        return getSupportInitOutput;
    }


    /**
     * 编辑众筹项目
     *
     * @param id          众筹编号
     * @param declaration 众筹联合发起
     */
    public void edite(String id, String declaration, String style) {
        Project project = projectService.get(id);
        project.setDeclaration(declaration);
        project.setStyle(style);
        projectService.update(project);
    }


    /**
     * 校正已筹金额
     *
     * @param projectId 众筹编号
     */
    public void revise(String projectId) {
        Project project = projectService.get(projectId);
        Float sum = supportService.sumByProjectId(projectId);
        if (!project.getActualAmount().equals(sum)) {
            Float amount = sum > project.getTargetAmount() ? project.getTargetAmount() : sum;
            amount = amount < 0 ? 0 : amount;
            project.setActualAmount(amount);
            projectService.update(project);
        }
    }

    /**
     * 众筹支持者列表
     *
     * @param page      分页参数
     * @param projectId 项目编号
     * @return 众筹支持列表
     */
    public List<SponsorOutput> sponsorList(Page page, String projectId) {

        Project project = projectService.get(projectId);
        SupportWithMember supportWithMember = new SupportWithMember();
        supportWithMember.setProjectId(projectId);
        supportWithMember.setStatus(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode());
        List<SupportWithMember> supportWithMemberList = supportService.sponsorListWithComment(supportWithMember, page);

        List<SponsorOutput> sponsorOutputList = LangUtils.transform(supportWithMemberList, new Function<SupportWithMember, SponsorOutput>() {
            @Nullable
            @Override
            public SponsorOutput apply(@Nullable SupportWithMember supportWithMember) {
                SponsorOutput sponsorOutput = SponsorOutput.transform(supportWithMember);
                return sponsorOutput;
            }
        });
        return sponsorOutputList;
    }

    /**
     * 众筹支持者列表-仅有基本信息
     *
     * @param page      分页参数
     * @param projectId 项目编号
     * @return 众筹支持列表
     */
    public List<SponsorOutput> sponsorListSimple(Page page, String projectId) {

        Project project = projectService.get(projectId);
        SupportWithMember supportWithMember = new SupportWithMember();
        supportWithMember.setProjectId(projectId);
        supportWithMember.setStatus(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode());
        List<SupportWithMember> supportWithMemberList = supportService.sponsorListSimple(supportWithMember, page);

        List<SponsorOutput> sponsorOutputList = LangUtils.transform(supportWithMemberList, new Function<SupportWithMember, SponsorOutput>() {
            @Nullable
            @Override
            public SponsorOutput apply(@Nullable SupportWithMember supportWithMember) {
                SponsorOutput sponsorOutput = SponsorOutput.transform(supportWithMember);
                return sponsorOutput;
            }
        });
        return sponsorOutputList;
    }


    /**
     * 获取当前众筹的百分比
     *
     * @param project
     * @return
     */
    public int getPercent(Project project) {
        double percent = BigDecimalUtils.div(project.getActualAmount(), project.getTargetAmount(), 5);
        int intPercent = BigDecimalUtils.amplify2int(percent, 1);
        int beforePercent = 0;
        for (int i = 1; i < 11; i++) {
            if (intPercent >= i && intPercent < i + 1) {
                beforePercent = i;
            }
        }
        return beforePercent;
    }

    /**
     * 格式化使用时间
     *
     * @param diffTime
     * @return
     */
    public String getUseTime(long diffTime) {
        long day = diffTime / (24 * 60 * 60 * 1000);
        long hour = (diffTime / (60 * 60 * 1000) - day * 24);
        long min = ((diffTime / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (diffTime / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        String useTime = "";
        if (day == 0 && hour == 0 && min == 0 && s == 0) {
            useTime = "0时0分";
        } else if (day == 0 && hour == 0 && min == 0) {
            useTime = s + "秒";
        } else {
            if (day > 0) {
                useTime += day + "天";
            }
            if (hour > 0) {
                useTime += hour + "小时";
            }
            if (min > 0) {
                useTime += min + "分钟";
            }
        /*if (s > 0) {
            useTime += s + "秒";
        }*/
        }
        return useTime;
    }

    /**
     * 格式化使用时间
     *
     * @param diffTime
     * @return
     */
    public String getUseTimeNew(long diffTime) {
        long day = diffTime / (24 * 60 * 60 * 1000);
        long hour = (diffTime / (60 * 60 * 1000) - day * 24);
        long min = ((diffTime / (60 * 1000)) - day * 24 * 60 - hour * 60);
        String useTime = "";
        if (day > 0) {
            useTime += day + "|天";
            if (hour > 0) {
                useTime += "|";
            }
        }
        if (hour > 0) {
            useTime += hour + "|小时";
            if (min > 0) {
                useTime += "|";
            }
        }
        if (min > 0) {
            useTime += min + "|分钟";
        }
        if (StringUtils.isEmpty(useTime)) {
            useTime += 1 + "|分钟";
        }
        return useTime;
    }

    /**
     * 获取累计用时
     *
     * @param projectId
     * @return
     */
    public String getAllUseTime(String projectId, Boolean formatFlag) {
        long diffTime = this.getCrowfundUserTime(projectId);
        if (formatFlag == null || formatFlag) {
            return getUseTime(diffTime);
        } else {
            return getUseTimeNew(diffTime);
        }
    }

    public Long getCrowfundUserTime(String projectId) {
        Project project = projectService.get(projectId);
        Support support = new Support();
        support.setProjectId(project.getId());
        support.setPayStatus(Constant.IS_SUCCESS);
        Support lastSupport = supportService.getLastSupport(support);

        Long startTime = project.getCreateDate().getTime();
        Long endTime;
        if (lastSupport == null) {
            endTime = System.currentTimeMillis();
        } else {
            endTime = lastSupport.getUpdateDate().getTime();
        }
        return endTime - startTime;
    }

    /**
     * 保存众筹排名
     *
     * @param percent  排名
     * @param payment  阶段金额
     * @param eventId  众筹事项
     * @param targetId 众筹项目
     * @param support  支持者
     * @param project  众筹
     */
    public void insertCrowdRank(Integer percent, Float payment, String eventId, String targetId, Support support, Project project) {
        CrowdfundRank crowdfundRank = new CrowdfundRank();
        crowdfundRank.setEventId(eventId);
        crowdfundRank.setPercent(percent);
        crowdfundRank.setProjectId(support.getProjectId());
        crowdfundRank.setTargetId(targetId);
        crowdfundRank.setPayment(payment);
        crowdfundRank.setArrivalTime(support.getUpdateDate());
        // 发起众筹的时间
        Long startTime = project.getCreateDate().getTime();
        // 阶段到达时间
        Long arrivalTime = support.getUpdateDate().getTime();
        Long diff = arrivalTime - startTime;
        crowdfundRank.setDiffTime(diff > 0 ? diff : 0);
        crowdfundRankService.insert(crowdfundRank);
    }


    /**
     * 众筹列表
     *
     * @param projectWithAuthor 查询参数
     * @param page              分页参数
     * @return 众筹列表
     */
    public List<ProjectForListOutput> listForActivity(ProjectWithAuthor projectWithAuthor, Page page) {
        List<ProjectWithAuthor> projectWithAuthorList = projectService.listPage(projectWithAuthor, page);

        List<ProjectForListOutput> list = LangUtils.transform(projectWithAuthorList, new Function<ProjectWithAuthor, ProjectForListOutput>() {
            @Nullable
            @Override
            public ProjectForListOutput apply(@Nullable ProjectWithAuthor projectWithAuthor) {
                ProjectForListOutput projectForListOutput = ProjectForListOutput.transform(projectWithAuthor);

                //二维码
                String filePath = fileBizService.getUploadCIPath("crowdfund", projectWithAuthor.getAuthorId());
                String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + projectWithAuthor.getId());
                projectForListOutput.setQrCodeUrl(qrCodeUrl);

                if (null != projectWithAuthor.getIsSuccess() && YesNoStatus.YES.getCode().equals(projectWithAuthor.getIsSuccess())) {
                    // 成功海报
                    String posterFilePath = String.format("%s/%s/", projectWithAuthor.getAuthorId(), "zcPoster");
                    String posterUrl = cosBizService.getPreviewPictureUrl(posterFilePath + projectWithAuthor.getId(), "png");
                    projectForListOutput.setPosterUrl(posterUrl);
                }
                return projectForListOutput;
            }
        });
        return list;
    }

    /**
     * 查询机构下所有众筹者
     *
     * @param targetAuthorId 机构编号
     * @param page           分页参数
     * @param isSuccess      状态
     * @return 众筹列表
     */
    public List<ProjectForListOutput> listForTargetAuthor(String targetAuthorId, Integer isSuccess, Page page) {

        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();

        //子账号数据过滤
        //projectWithAuthor.setTargetAuthorId(targetAuthorId);
        List<String> orgIds = memberGroupService.getChildWithMy(targetAuthorId);
        projectWithAuthor.setOrgIds(orgIds);

        if (null == isSuccess) {
            projectWithAuthor.setSort(3);
        } else {
            projectWithAuthor.setSort(4);
        }
        projectWithAuthor.setIsSuccess(isSuccess);
        List<ProjectWithAuthor> projectWithAuthorList = projectService.listPage(projectWithAuthor, page);
        List<ProjectForListOutput> list = LangUtils.transform(projectWithAuthorList, new Function<ProjectWithAuthor, ProjectForListOutput>() {
            @Nullable
            @Override
            public ProjectForListOutput apply(@Nullable ProjectWithAuthor projectWithAuthor) {
                ProjectForListOutput projectForListOutput = ProjectForListOutput.transform(projectWithAuthor);

                //二维码
                String filePath = fileBizService.getUploadCIPath("crowdfund", projectWithAuthor.getAuthorId());
                String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + projectWithAuthor.getId());
                projectForListOutput.setQrCodeUrl(qrCodeUrl);

                // 众筹成功海报图片路径
                if (YesNoStatus.YES.getCode().equals(projectWithAuthor.getIsSuccess())) {
                    String posterFilePath = String.format("%s/%s/", projectWithAuthor.getAuthorId(), "zcPoster");
                    String posterUrl = cosBizService.getPreviewPictureUrl(posterFilePath + projectWithAuthor.getId(), "png");
                    projectForListOutput.setPosterUrl(posterUrl);
                }
                return projectForListOutput;
            }
        });
        return list;
    }

    /**
     * 获取绘制海报的数据
     *
     * @param projectId 众筹id
     * @return
     */
    /**
     * 获取绘制海报的数据
     *
     * @param projectId 众筹id
     * @return
     */
    public ProjectPosterOutput getPaintPosterData(String projectId, CrowdfundEvent crowdfundEvent, Member crowdfundMember,
                                                  Activity activity, MemberGroup orgMember) {
        try {
            // 众筹者
            if (crowdfundMember == null) {
                throw new BusinessException(PartyCode.IS_NO_DATA, "用户为空");
            }
            if (activity == null) {
                throw new BusinessException(PartyCode.IS_NO_DATA, "项目为空");
            }
            ProjectPosterOutput posterOutput = new ProjectPosterOutput();
            posterOutput.setProjectId(projectId);
            Project project = projectService.get(projectId);
            // 支持人数
            posterOutput.setSupportNum(project.getFavorerNum());
            // 昵称
            posterOutput.setNickName(crowdfundMember.getRealname());
            // 公司
            posterOutput.setCompany(crowdfundMember.getCompany());
            // 头像
            posterOutput.setLogo(crowdfundMember.getLogo());
            posterOutput.setAuthorId(crowdfundMember.getId());
            // 金额
            posterOutput.setMoney(project.getActualAmount().doubleValue());
            // 标题
            posterOutput.setProjectTitle(activity.getTitle());
            // 海报
            posterOutput.setProjectPic(activity.getPic());
            // 二维码
            String filePath = fileBizService.getUploadCIPath(activity.getMember(), "zcActivity");
            String detailFileName = "detail_" + activity.getId();
            String detailQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
            posterOutput.setQrcodeUrl(detailQrCodeUrl);
            if (YesNoStatus.NO.getCode().equals(crowdfundEvent.getIsMultiple())) {
                // 开始时间
                posterOutput.setStartDate(DateUtils.formatDate(activity.getStartTime(), "yyyy.MM.dd"));
                // 地点Map
                Map<String, String> addressMap = Maps.newHashMap();
                String address = activityService.getShowAddressMap(activity, addressMap);
                posterOutput.setPlaceMap(addressMap);
                posterOutput.setPlace(address);

            }else{
                EventGradation ongoingGradation = eventGradationService.findOngoingGradation(activity.getEventId());
                // 开始时间
                posterOutput.setStartDate(DateUtils.formatDate(ongoingGradation.getEndTime(), "yyyy.MM.dd"));

                // 地点Map
                Map<String, String> addressMap = Maps.newHashMap();
                String address = eventGradationService.getShowAddressMap(ongoingGradation, addressMap);
                posterOutput.setPlaceMap(addressMap);
                posterOutput.setPlace(address);
            }
            // 发布者
            if (orgMember != null) {
                posterOutput.setOrgName(orgMember.getRealname());
            }
            posterOutput.setPublisherId(activity.getMember());
            posterOutput.setActivityId(activity.getId());
            // 众筹用时
            posterOutput.setIsMultiple(crowdfundEvent.getIsMultiple());
            if (YesNoStatus.YES.getCode().equals(crowdfundEvent.getIsMultiple())) {
                List<ProjectGradation> projectGradations = projectGradationService.getSuccessListForProjectId(projectId);
                Long diffTime = 0L;
                Double price = 0d;
                for (ProjectGradation projectGradation : projectGradations) {
                    diffTime += projectGradation.getUseTime();
                    price = BigDecimalUtils.add(projectGradation.getTargetAmount(), price);
                }

                long oneMonthMs = 30L * 24L * 60L * 60L * 1000L;
                long oneDayMs = 24L * 60L * 60L * 1000L;
                long oneHourMs = 60 * 60 * 1000;
                long oneMinMs = 60 * 1000;

                long month = diffTime / oneMonthMs;
                long monthAll = month * oneMonthMs;

                long day = (diffTime - monthAll) / oneDayMs;
                long dayAll = day * oneDayMs;

                posterOutput.setUseTimeMonth(month);
                posterOutput.setUserTimeDay(day);
                posterOutput.setMoney(BigDecimalUtils.round(price, 2));
                posterOutput.setSuccessCount(projectGradations.size());

                if (month <= 0 && day <= 0) {
                    posterOutput.setUserTimeDay(1L);
                }
            } else {
                Long diffTime = project.getUseTime();

                long month = diffTime / (30 * 24 * 60 * 60 * 1000);
                long day = diffTime / (24 * 60 * 60 * 1000);
                long hour = (diffTime / (60 * 60 * 1000) - day * 24);
                long min = ((diffTime / (60 * 1000)) - day * 24 * 60 - hour * 60);

                posterOutput.setUserTimeDay(day);
                posterOutput.setUserTimeHour(hour);
                posterOutput.setUserTimeMinute(min);

                if (day <= 0 && hour <= 0 && min <= 0) {
                    posterOutput.setUserTimeMinute(1L);
                }
            }
            return posterOutput;
        } catch (BusinessException e) {
            logger.error("获取绘制海报数据异常BusinessException", e);
            return null;
        } catch (Exception e) {
            logger.error("获取绘制海报数据异常Exception", e);
            return null;
        }
    }

    /**
     * 绘制众筹海报
     *
     * @param projectId 众筹id
     * @return 文件字节数组
     */
    public byte[] paintProjectPoster(String projectId, Member crowdfundMember, MemberGroup orgMember, Activity activity) {
        CrowdfundEvent crowdfundEvent = crowdfundEventService.findByProjectId(projectId);
        ProjectPosterOutput posterOutput = getPaintPosterData(projectId, crowdfundEvent, crowdfundMember, activity, orgMember);
        return getSuccessPoster(crowdfundEvent, posterOutput);
    }

    /**
     * 绘制众筹海报
     *
     * @param projectId 众筹id
     * @return 文件字节数组
     */
    public byte[] paintProjectPoster(String projectId) {
        Project project = projectService.get(projectId);
        Member crowdfundMember = memberService.get(project.getAuthorId());
        TargetProject targetProject = targetProjectService.findByProjectId(project.getId());
        Activity activity = activityService.get(targetProject.getTargetId());
        MemberGroup orgMember = memberGroupService.get(activity.getMember());
        CrowdfundEvent crowdfundEvent = crowdfundEventService.findByProjectId(projectId);
        ProjectPosterOutput posterOutput = getPaintPosterData(projectId, crowdfundEvent, crowdfundMember, activity, orgMember);
        return getSuccessPoster(crowdfundEvent, posterOutput);
    }

    private byte[] getSuccessPoster(CrowdfundEvent crowdfundEvent, ProjectPosterOutput posterOutput) {
        if (posterOutput == null) {
            return null;
        }

        try {
            ImageIO.read(new URL(posterOutput.getQrcodeUrl()));
        } catch (Exception e) {
            makeZcActivityDetailQrCode(crowdfundEvent, posterOutput);
        }

        return paintProjectPosterBiz.projectPosterUploadCI(posterOutput);
    }

    /**
     * 绘制支持海报
     *
     * @param projectId 众筹id
     * @return 文件字节数组
     */
    public byte[] paintSupportersPoster(String projectId, String authorId, String amount, Member crowdfundMember,
                                        MemberGroup orgMember, Activity activity, Member supportMember) throws Exception {
        CrowdfundEvent crowdfundEvent = crowdfundEventService.findByProjectId(projectId);
        ProjectPosterOutput posterOutput = getPaintPosterData(projectId, crowdfundEvent, crowdfundMember, activity, orgMember);
        if (null != supportMember) {
            posterOutput.setSupportLogo(supportMember.getLogo());
        }
        return getSupportPoster(authorId, amount, crowdfundEvent, posterOutput);
    }

    /**
     * 绘制支持海报
     *
     * @param projectId 众筹id
     * @return 文件字节数组
     */
    public byte[] paintSupportersPoster(String projectId, String authorId, String amount) throws Exception {
        Project project = projectService.get(projectId);
        Member crowdfundMember = memberService.get(project.getAuthorId());
        TargetProject targetProject = targetProjectService.findByProjectId(project.getId());
        Activity activity = activityService.get(targetProject.getTargetId());
        MemberGroup orgMember = memberGroupService.get(activity.getMember());
        CrowdfundEvent crowdfundEvent = crowdfundEventService.findByProjectId(projectId);
        ProjectPosterOutput posterOutput = getPaintPosterData(projectId, crowdfundEvent, crowdfundMember, activity, orgMember);
        return getSupportPoster(authorId, amount, crowdfundEvent, posterOutput);
    }

    private byte[] getSupportPoster(String authorId, String amount, CrowdfundEvent crowdfundEvent,
                                    ProjectPosterOutput posterOutput) throws Exception {
        String supportLogo = "";
        byte[] barr = null;
        if (posterOutput == null) {
            return null;
        }
        try {
            if (StringUtils.isEmpty(posterOutput.getSupportLogo())) {
                Member supportersObj = memberService.get(authorId);

                if (null != supportersObj) {
                    supportLogo = supportersObj.getLogo();
                }
            } else {
                supportLogo = posterOutput.getSupportLogo();
            }
            //获取支持海报字节arr

            ImageIO.read(new URL(posterOutput.getQrcodeUrl()));
        } catch (Exception e) {
            makeZcActivityDetailQrCode(crowdfundEvent, posterOutput);
        }

        return paintProjectPosterBiz.getsupportersPosters(posterOutput, supportLogo, amount);
    }

    private void makeZcActivityDetailQrCode(CrowdfundEvent crowdfundEvent, ProjectPosterOutput posterOutput) {
        try {
            String filePath = fileBizService.getUploadCIPath(posterOutput.getPublisherId(), "zcActivity");
            if (YesNoStatus.NO.getCode().equals(crowdfundEvent.getIsMultiple())) {
                /*** 众筹项目详情二维码 ***/
                String xqFileName = "detail_" + posterOutput.getActivityId();
                String detailContent = "project/target_client_detail.html?id=" + posterOutput.getActivityId();
                String qrcodeUrl = fileBizService.uploadCloudOut(xqFileName, filePath, detailContent, posterOutput.getPublisherId());
                posterOutput.setQrcodeUrl(qrcodeUrl);
            } else if (YesNoStatus.YES.getCode().equals(crowdfundEvent.getIsMultiple())) {
                /*** 众筹项目详情二维码 ***/
                String xqFileName = "detail_" + posterOutput.getActivityId();
                String detailContent = "project/target_multi_detail.html?id=" + posterOutput.getActivityId();
                String qrcodeUrl = fileBizService.uploadCloudOut(xqFileName, filePath, detailContent, posterOutput.getPublisherId());
                posterOutput.setQrcodeUrl(qrcodeUrl);
            }
        } catch (Exception ex) {
            logger.error("众筹项目二维码生成异常", ex);
        }
    }

    /**
     * 获取众筹成功海报
     *
     * @param projectId 众筹编号
     * @return 众筹海报图片路径
     */
    public String getProjectPoster(String projectId) {
        Project project = projectService.get(projectId);
        CrowdfundEvent crowdfundEvent = crowdfundEventService.findByProjectId(projectId);

        if (null != crowdfundEvent) {
            if (YesNoStatus.NO.getCode().equals(crowdfundEvent.getIsMultiple())) {
                if (!YesNoStatus.YES.getCode().equals(project.getIsSuccess())) {
                    throw new BusinessException(110, "该众筹状态不是成功的");
                }
            }
        }
        String filePath = String.format("%s/%s/", project.getAuthorId(), "zcPoster");
        String resourceUrl = cosBizService.getPreviewPictureUrl(filePath + projectId, "png");
        try {
            ImageIO.read(new URL(resourceUrl));
        } catch (IOException e) {
            logger.info("众筹海报不存在，重新绘制上传");
            byte[] bytes = paintProjectPoster(projectId);
            if (bytes == null) {
                throw new BusinessException(666, "获取海报数据异常");
            }
        }
        resourceUrl = cosBizService.getPreviewPictureUrl2(filePath + projectId, "png");
        return resourceUrl;
    }



    /**
     * 获取用户的众筹信息
     *
     * @param authorId 用户id
     * @param eventId  主题id
     * @return
     */
    public String getProjectId(String authorId, String eventId) {
        List<Project> projects = projectService.listForAuthorId(authorId, eventId);
        if (projects.size() == 0) {
            return null;
        } else if (projects.size() == 1) {
            return projects.get(0).getId();
        } else {
            Collections.sort(projects, (o1, o2) -> o2.getActualAmount().compareTo(o1.getActualAmount()));
            return projects.get(0).getId();
        }
    }

    /**
     * 查询活动下的众筹__多场
     *
     * @param isSuccess 是否筹集成功
     * @param targetId  目标编号
     * @param page      分页参数
     * @return 众筹列表
     */
    public List<ProjectForActivityOutput> gradationProjectForActivityList(boolean isSuccess, String targetId, Page page) {
        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();

        //众筹成功？
        Integer success = isSuccess ? 1 : 0;
        projectWithAuthor.setIsSuccess(success);
        projectWithAuthor.setTargetId(targetId);
        // 不按照众筹截止时间排序
        projectWithAuthor.setSort(2);
        List<ProjectWithAuthor> projectWithAuthorList = projectService.gradationListWithAuthorPage(projectWithAuthor, page);
        return this.transformOutput(projectWithAuthorList);
    }

    /**
     * 查询活动下兄弟活动的众筹__多场
     *
     * @param isSuccess 是否筹集成功
     * @param targetId  目标编号
     * @param page      分页参数
     * @return 众筹列表
     */
    public List<ProjectForActivityOutput> gradationProjectForBrotherList(boolean isSuccess, String targetId, Page page) {
        Activity activity = activityService.get(targetId);
        if (null == activity || Strings.isNullOrEmpty(activity.getEventId())) {
            return Collections.EMPTY_LIST;
        }

        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();
        //众筹成功？
        Integer success = isSuccess ? 1 : 0;
        projectWithAuthor.setIsSuccess(success);
        projectWithAuthor.setExcludeTargetId(targetId);
        projectWithAuthor.setEventId(activity.getEventId());
        List<ProjectWithAuthor> projectWithAuthorList = projectService.gradationListWithAuthorPage(projectWithAuthor, page);
        return this.transformOutput(projectWithAuthorList);
    }

    /**
     * 查询联合发起下的众筹
     *
     * @param isSuccess   是否众筹成功
     * @param representId 联合发起编号
     * @param page        分页参数
     * @return 众筹列表
     */
    public List<ProjectForActivityOutput> gradationProjectForRepresentList(boolean isSuccess, String representId, Page page) {
        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();

        //众筹成功？
        Integer success = isSuccess ? 1 : 0;
        projectWithAuthor.setIsSuccess(success);
        projectWithAuthor.setRelationId(representId);
        List<ProjectWithAuthor> projectWithAuthorList = projectService.gradationListWithAuthorPage(projectWithAuthor, page);
        return this.transformOutput(projectWithAuthorList);
    }

    /**
     * 活动下所有的众筹__多场
     *
     * @param isSuccess 是否筹集成功
     * @param targetId  目标编号
     * @param page      分页参数
     * @return 众筹列表
     */
    public List<ProjectForActivityOutput> gradationProjectForAllList(boolean isSuccess, String targetId, Page page) {
        Activity activity = activityService.get(targetId);
        if (null == activity) {
            return Collections.EMPTY_LIST;
        }

        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();
        if (Strings.isNullOrEmpty(activity.getEventId())) {
            projectWithAuthor.setTargetId(targetId);
        } else {
            projectWithAuthor.setEventId(activity.getEventId());
        }

        //众筹成功？
        Integer success = isSuccess ? 1 : 0;
        projectWithAuthor.setIsSuccess(success);
        List<ProjectWithAuthor> projectWithAuthorList = projectService.gradationListWithAuthorPage(projectWithAuthor, page);
        return this.transformOutput(projectWithAuthorList);
    }

    /**
     * 保存众筹排名
     *
     * @param afterPercent
     * @param beforePercent
     * @param activity
     * @param support
     * @param project
     */
    public void doCrowdRank(int afterPercent, int beforePercent, Activity activity, Support support, Project project) {
        int newAfterPercent = afterPercent > 10 ? 10 : afterPercent;
        // 保存众筹排名
        if (newAfterPercent > beforePercent) {
            insertCrowdRank(newAfterPercent, project.getTargetAmount(), activity.getEventId(), activity.getId(), support, project);
        }

        int result = newAfterPercent - beforePercent;
        if (result > 1) {
            for (int i = 1; i < result; i++) {
                insertCrowdRank(beforePercent + i, project.getTargetAmount(), activity.getEventId(), activity.getId(), support, project);
            }
        }
    }

    public void testPayReset(String orderId) {
        OrderForm orderForm = orderFormService.get(orderId);
        orderForm.setStatus(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
        orderFormService.update(orderForm);

        OrderTrade orderTrade = orderTradeService.findByOrderId(orderId);
        if (null != orderTrade) {
            orderTradeService.delete(orderTrade.getId());
        }

        Support support = supportService.findByOrderId(orderId);
        support.setPayStatus(YesNoStatus.NO.getCode());
        supportService.update(support);

        TargetProject targetProject = targetProjectService.findByProjectId(support.getProjectId());

        Project dbProject = projectService.get(targetProject.getProjectId());
        Activity dbActivity = activityService.get(targetProject.getTargetId());
        try {
            crowdfundReviseBizService.reviseProjectData(dbProject);
            crowdfundReviseBizService.reviseTargetData(dbActivity);
        } catch (Exception e) {
            logger.error("支持完成后, 立即校验众筹和活动数据异常", e);
        }
    }
}
